package com.xinzhi.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xinzhi.domain.User;
import com.xinzhi.domain.vo.LoginVo;
import com.xinzhi.service.LoginService;
import com.xinzhi.service.UserService;

import com.xinzhi.utils.Result;
import com.xinzhi.utils.lsJWTUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
private static final  String slat ="$qwe234";
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public Result login(LoginVo loginvo) {
        /**
         * 1:检查参数是否合法
         * 2根据用户名和密码去user表种查询是否存在
         * 3如果不存在登录失败
         * 4如果存在：使用jwt 生成token 返回给前端。
         * 5 token放入redis中，redis token:User 信息 设置过期时候
         * （登录认证时，先认证token 字符串是否合法，去redis认证是否存在）
         */
        String username = loginvo.getUsername();
        String password = loginvo.getPassword();
        if (StringUtils.isBlank(username)||StringUtils.isBlank(password)) {
            return Result.error(10001,"参数有误");
        }
        password = DigestUtils.md5Hex(password + slat );
//        password = DigestUtils.md5Hex(password);
        User user = userService.findUser(username, password);


        if (user == null){
            return Result.error("账号或密码错误！！！");
        }

        String token =  lsJWTUtils.createToken(user.getUserId());

        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
        return Result.ok(token);

    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_"+ token);
        return Result.ok(null);
    }

    @Override
    public User checkToken(String token) {
        if (StringUtils.isBlank(token)){
            return  null;
        }

        Map<String, Object> stringObjectMap = lsJWTUtils.checkToken(token);
        if (stringObjectMap == null){
            return null;
        }
//        boolean b = lsJWTUtils.checkToken(token);
//        if (b){
//            return null;
//        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (StringUtils.isBlank(userJson)){
            return null;
        }
        User User = JSON.parseObject(userJson, User.class);
        return User;
    }

}
